﻿using Consul;
using Microsoft.Extensions.Configuration;
using System;

namespace Contione.Microservices.ConsulRegist
{
    public static class ConsulHelper
    {
        public static async void ConsulRegist(this IConfiguration configuration)
        {
            string ip = configuration["ip"];
            int port = int.Parse(configuration["port"]);
            int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);
            string serviceName = configuration["ServiceName"];
            Uri consulUrl = new Uri(configuration["ConsulAddress"]);
            string consulCenter = configuration["ConsulCenter"];

            //连接 Consul 注册服务
            using (ConsulClient client = new ConsulClient(c => { c.Address = consulUrl; c.Datacenter = consulCenter; }))
            {
                await client.Agent.ServiceRegister(new AgentServiceRegistration()
                {
                    ID = $"{serviceName} {ip}:{port}",
                    Name = serviceName,
                    Address = ip,
                    Port = port,
                    Tags = new string[] { weight.ToString() },
                    Check = new AgentServiceCheck()
                    {
                        Interval = TimeSpan.FromSeconds(12),
                        HTTP = $"http://{ip}:{port}/api/health",
                        Timeout = TimeSpan.FromSeconds(5),
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
                    }
                });
            }
            Console.WriteLine($"{ip}:{port}--weight:{weight}");
        }
    }
}
